package com.example.himalaya.view.activity;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.example.himalaya.R;
import com.example.himalaya.view.adapters.SearchContentAdapter;
import com.example.himalaya.view.adapters.SearchIndicatorAdapter;
import com.example.himalaya.view.adapters.SearchRecommendAdapter;
import com.example.himalaya.base.BaseActivity;
import com.example.himalaya.view.callback.ISearchViewCallBack;
import com.example.himalaya.presenters.SearchPresenter;
import com.example.himalaya.utils.LogUtil;
import com.example.himalaya.view_component.FlowTextLayout;
import com.example.himalaya.view_component.UILoader;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.album.Announcer;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.model.word.HotWord;
import com.ximalaya.ting.android.opensdk.model.word.QueryResult;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;

import java.util.ArrayList;
import java.util.List;

public class SearchViewActivity extends BaseActivity implements ISearchViewCallBack {

    // Constant
    public String TAG = "SearchViewActivity";
    public static final int TIME_SHOW_IMM = 800;

    // UI object
    private View mBackBtn;
    private EditText mInputBox;
    private TextView mSearchBtn;
    private FrameLayout mResultContainer;
    private ImageView mDeleteBth;
    private RecyclerView mSearchRecommendList;

    // System object
    private InputMethodManager mInputMethodManager;

    // Other UI Object
    private UILoader mUILoader = null;
    private FlowTextLayout mFlowTextLayout;

    // Logic Object
    private SearchPresenter mSearchPresenter;

    private SearchRecommendAdapter mRecommendAdapter;

    // Flag
    private boolean mNeedSuggestWords = true;
    private MagicIndicator mSearchIndicator;
    private ViewPager mSearchPager;
    private CommonNavigator mCommonNavigator;
    private SearchIndicatorAdapter mSearchIndicatorAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);


        initVariable();

        initUiLoader();

        initPresenter();

        initListener();

        initData();

        initView();
    }

    private void initUiLoader() {
        if (mUILoader == null) {
            mUILoader = new UILoader(this) {
                @Override
                protected View getSuccessView(ViewGroup container) {
                    return createSuccessView(container);
                }

                @Override
                protected View getEmptyView() {

                    View itemView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_empty_view, this, false);

                    TextView tipsView = itemView.findViewById(R.id.tips_for_empty);

                    tipsView.setText(R.string.tips_for_empty_search);
                    return itemView;
                }
            };

            if (mUILoader.getParent() instanceof ViewGroup) {
                ((ViewGroup) mUILoader.getParent()).removeView(mUILoader);
            }

            mResultContainer.removeAllViews();
            mResultContainer.addView(mUILoader);
        }
    }


    private void initListener() {

        // 点击返回的事件
        mBackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        // 点击搜索关键字的事件
        mSearchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String keyword = mInputBox.getText().toString().trim();

                if (TextUtils.isEmpty(keyword)) {
                    Toast.makeText(SearchViewActivity.this, "请输入内容在搜索", Toast.LENGTH_LONG).show();
                    return;
                }

                // 让逻辑层记住当前用户输入的关键字
                mSearchPresenter.setCurrentKeyword(keyword);

                mSearchIndicator.setVisibility(View.VISIBLE);
                mSearchPager.setVisibility(View.VISIBLE);

            }
        });


        mInputBox.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence keyword, int start, int before, int count) {

                if (TextUtils.isEmpty(keyword)) {
                    mSearchPresenter.getHotWord();
                    mDeleteBth.setVisibility(View.GONE);

                } else {

                    // 触发联想查询
                    if (mNeedSuggestWords) {
                        getSuggestWord(keyword);
                    } else {
                        mNeedSuggestWords = true;
                    }

                    mDeleteBth.setVisibility((View.VISIBLE));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });



        /*
          点击重新刷新的方法
         */
        mUILoader.setOnRetryClickListener(new UILoader.OnRetryClickListener() {
            @Override
            public void onRetryClick() {
                if (mSearchPresenter != null) {
                    mSearchPresenter.reSearch();
                    mUILoader.updateStatus(UILoader.UIStatus.LOADING);
                }
            }
        });


        // 删除输入的按钮事件
        mDeleteBth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mInputBox.setText("");
            }
        });


        // 点击热词进行搜索的事件
        if (mRecommendAdapter != null) {
            mRecommendAdapter.setItemClickListener(new SearchRecommendAdapter.ItemClickListener() {
                @Override
                public void onItemClick(String keyword) {
                    // LogUtil.d(TAG, "mRecommendAdapter  keyword -->" + keyword);

                    mNeedSuggestWords = false;

                    switch2Search(keyword);
                }
            });
        }
    }

    private void initData() {
        // 去拿热词
        mSearchPresenter.getHotWord();
    }

    private void initVariable() {
        // UI Object
        mBackBtn = this.findViewById(R.id.back_btn);
        mInputBox = this.findViewById(R.id.input_box);
        mDeleteBth = this.findViewById(R.id.search_input_delete);
        mSearchBtn = this.findViewById(R.id.search_btn);
        mResultContainer = this.findViewById(R.id.search_container);

        // System Object
        mInputMethodManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);

        // Other UI Object
    }

    private void initPresenter() {
        mSearchPresenter = SearchPresenter.getSearchPresenter();
        // 注册UI更新的接口
        mSearchPresenter.registerViewCallback(this);


    }


    private void initView() {

        // 隐藏删除键
        mDeleteBth.setVisibility(View.GONE);

        // 弹出输入键盘
        mInputBox.postDelayed(new Runnable() {
            @Override
            public void run() {
                mInputBox.requestFocus();
                mInputMethodManager.showSoftInput(mInputBox, InputMethodManager.SHOW_IMPLICIT);
            }
        }, TIME_SHOW_IMM);
    }

    /**
     * 生成搜索成功界面的方法
     *
     * @param container 不知道的容器
     * @return 显示热词的界面
     */
    private View createSuccessView(ViewGroup container) {

        View successView = LayoutInflater.from(this).inflate(R.layout.search_result_layout, container, false);

        initSuccessVariable(successView);


        initSuccessAdapter();

        initSuccessListener();

        initSuccessView();


        return successView;
    }

    private void initSuccessVariable(View successView) {
        // UI Object
//        mResultListView = successView.findViewById(R.id.search_result_album_rv);
        mSearchRecommendList = successView.findViewById(R.id.search_recommend_list);
        mSearchPager = successView.findViewById(R.id.search_pager);

        // Other UI Object
        // 显示热词的
        mFlowTextLayout = successView.findViewById(R.id.recommend_hot_word_view);

        mSearchIndicator = successView.findViewById(R.id.search_indicator);

        // Other Logic Object
        mCommonNavigator = new CommonNavigator(this);
    }

    private void initSuccessListener() {

        mSearchIndicatorAdapter.setOnIndicatorTapClickListener(new SearchIndicatorAdapter.OnIndicatorTapClickListener() {
            @Override
            public void onTabClick(int index) {
                LogUtil.d(TAG, "Click index is ->" + index);
                if (mSearchPager != null) {
                    mSearchPager.setCurrentItem(index);
                }
            }
        });


        /*
           点击热词触发的事件
         */
        mFlowTextLayout.setClickListener(new FlowTextLayout.ItemClickListener() {
            @Override
            public void onItemClick(String keyWord) {
                // Toast.makeText(SearchViewActivity.this, keyWord, Toast.LENGTH_LONG).show();

                // 不需要相关的联想词显示
                mNeedSuggestWords = false;

                switch2Search(keyWord);
            }
        });
    }

    private void initSuccessView() {
        // 设置背景颜色
        mSearchIndicator.setBackgroundColor(this.getResources().getColor(R.color.color_main));

        mCommonNavigator.setAdjustMode(true);

        mSearchIndicator.setNavigator(mCommonNavigator);
        // 绑定两个控件，同步
        ViewPagerHelper.bind(mSearchIndicator, mSearchPager);


        // 设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mSearchRecommendList.setLayoutManager(layoutManager);
        mSearchRecommendList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = UIUtil.dip2px(view.getContext(), 2);
                outRect.bottom = UIUtil.dip2px(view.getContext(), 2);
                outRect.left = UIUtil.dip2px(view.getContext(), 5);
                outRect.right = UIUtil.dip2px(view.getContext(), 5);
            }
        });
    }

    private void initSuccessAdapter() {
        // 创建内容设配器
        FragmentManager fragmentManager = getSupportFragmentManager();
        SearchContentAdapter searchContentAdapter = new SearchContentAdapter(fragmentManager);
        mSearchPager.setAdapter(searchContentAdapter);

        // 指示器的适配器
        mSearchIndicatorAdapter = new SearchIndicatorAdapter(this);
        mCommonNavigator.setAdapter(mSearchIndicatorAdapter);

        // 推荐搜索内容的适配器
        mRecommendAdapter = new SearchRecommendAdapter();

        mSearchRecommendList.setAdapter(mRecommendAdapter);
    }



    private void switch2Search(String keyWord) {

        if (TextUtils.isEmpty(keyWord)) {
            Toast.makeText(SearchViewActivity.this, "请输入内容在搜索", Toast.LENGTH_LONG).show();
            return;
        }

        // 把热词搜索一下内容
        mInputBox.setText(keyWord);
        mInputBox.setSelection(keyWord.length());


        if (mSearchPresenter != null) {
            mSearchPresenter.setCurrentKeyword(keyWord);
        }

        // 进入搜索界面
        if (mUILoader != null) {
            mUILoader.updateStatus(UILoader.UIStatus.LOADING);
        }
    }

    /**
     * 获取联想的关键字
     *
     * @param keyword 关键字
     */
    private void getSuggestWord(CharSequence keyword) {
        if (mSearchPresenter != null) {
            mSearchPresenter.getRecommendWord(keyword.toString());
        }
    }

    @Override
    public void onSearchAlbumLoaded(List<Album> result) {
        // 隐藏键盘
        mInputMethodManager.hideSoftInputFromWindow(mInputBox.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

        // 隐藏一些组件
        hideSuccessView();

        if (result == null) {
            mUILoader.updateStatus(UILoader.UIStatus.ERROR);
        } else {
            handleSearchResult(result.size());
        }
    }

    @Override
    public void onSearchTrackLoaded(List<Track> result) {
        // 隐藏键盘
        mInputMethodManager.hideSoftInputFromWindow(mInputBox.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

        // 隐藏一些组件
        hideSuccessView();

        if (result == null) {
            mUILoader.updateStatus(UILoader.UIStatus.ERROR);
        } else {
            handleSearchResult(result.size());
        }
    }

    @Override
    public void onSearchAnnouncerLoaded(List<Announcer> result) {

    }

    private void handleSearchResult(int result) {

        if (result == 0) {
            // 数据为空
            if (mUILoader != null) {
                mUILoader.updateStatus(UILoader.UIStatus.EMPTY);
            }
        } else {
            // 如果数据不为空就设置数据
            mUILoader.updateStatus(UILoader.UIStatus.SUCCESS);

            mSearchIndicator.setVisibility(View.VISIBLE);
            mSearchPager.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 热词回来后
     *
     * @param hotWordList 热词列表
     */
    @Override
    public void onHotWorldLoaded(List<HotWord> hotWordList) {

        // 先显示 和 隐藏UI组件
        hideSuccessView();
        mFlowTextLayout.setVisibility(View.VISIBLE);

        if (mUILoader != null) {
            mUILoader.updateStatus(UILoader.UIStatus.SUCCESS);
        }

        List<String> hotWords = new ArrayList<>();

        // 这样写感觉不对
        hotWords.clear();

        for (HotWord hotWord : hotWordList) {
            String searchWord = hotWord.getSearchword();

            hotWords.add(searchWord);
        }

        // 更新UI
        mFlowTextLayout.setTextContents(hotWords);
    }

    @Override
    public void onLoadMoreAlbumResult(List<Album> result, boolean isOkay) {

    }

    @Override
    public void onLoadMoreAnnouncerResult(List<Announcer> result, boolean isOkay) {

    }

    @Override
    public void onLoadMoreTrackResult(List<Track> result, boolean isOkay) {

    }

    @Override
    public void onRecommendWorldLoaded(List<QueryResult> keyWordList) {
        // 关键字的联想
        LogUtil.d(TAG, "keyWordList size -->" + keyWordList.size());

        if (mRecommendAdapter != null) {
            mRecommendAdapter.setData(keyWordList);
        }

        // 控制UI的状态
        if (mUILoader != null) {
            mUILoader.updateStatus(UILoader.UIStatus.SUCCESS);
        }

        // 控制显示隐藏
        hideSuccessView();

        mSearchRecommendList.setVisibility(View.VISIBLE);
    }

    private void hideSuccessView() {
        mSearchRecommendList.setVisibility(View.GONE);
        mFlowTextLayout.setVisibility(View.GONE);
        mSearchIndicator.setVisibility(View.GONE);
        mSearchPager.setVisibility(View.GONE);
    }

    /**
     * 搜索热词出错
     *
     * @param errorCode 错误码
     * @param errorMsg  错误信息
     */
    @Override
    public void onError(int errorCode, String errorMsg) {
        if (mUILoader != null) {
            mUILoader.updateStatus(UILoader.UIStatus.ERROR);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mSearchPresenter != null) {
            mSearchPresenter.unRegisterViewCallback(this);
            mSearchPresenter = null;
        }
    }
}
